//
//  YDHomeViewController.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2017/11/3.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDHomeViewController.h"
#import "YDHomeTopView.h"
#import "YDHomeTopBarView.h"
#import "YDHomeTransactionDynamicsCell.h"//交易动态cell
#import "YDHomeRecommendedStockCell.h"//推荐股票cell
#import "YDHomeOptionsCell.h"

#import "YDHomeTableViewHeaderView.h"//
#import "YDQHomeTableViewHeader.h"
#import "YDStockSearchViewController.h"//搜索界面
#import "YDQuestionController.h"//问答界面

#import "YDHomeDynamicModel.h"
#import "YDHomeReModel.h"
#import "YDHomeCarsoulModel.h"
#import "YDHomeRotationModel.h"
#import "YDHomeMarketModel.h"
#import "YDHomeOptionsDynamicModel.h"


#import "YDBuyStrategyController.h"//点买策略
#import "YDAdvertViewController.h"
#import "YDTuiGuangViewController.h"
#import "YDFreeAdvertViewController.h"
#import "YDVerticalStockBuyController.h"
#import "YDStockMarketDetailController.h"
#import "YDBaseOptionsStockModeController.h"
#import "YDBuyOptionsViewController.h"
#import "YDOptionsModeController.h"
#import "YDWebViewController.h"
@interface YDHomeViewController ()<UITableViewDelegate , UITableViewDataSource , SYHomeTopBarViewDelegate , SYHomeTopViewDelegate , SYHomeOptionsCellDelegate>

//显示数据类型
@property (nonatomic , assign) SYHomeViewControllerDataStyle dataStyle;


//tableView
@property (nonatomic , weak) UITableView *tableView;
//顶部视图
@property (nonatomic , weak) YDHomeTopView *topView;
//顶部工具栏
@property (nonatomic , weak) YDHomeTopBarView *topBarView;

//定时器相关
//定时器
@property (nonatomic , strong) NSTimer *marketTimer;
//是不是正在刷新
@property (nonatomic , assign) BOOL marketIsRunning;


//模型数组相关
//交易动态
@property (nonatomic , strong) NSMutableArray *dynamicsModelArray;
//期权交易动态
@property (nonatomic , strong) NSMutableArray *optionsDynamicsModelArray;
//推荐股票
@property (nonatomic , strong) NSMutableArray *reModelArray;
//轮播
@property (nonatomic , strong) NSMutableArray *carsoulModelArray;
//盛放轮播图片链接的数组
@property (nonatomic , strong) NSMutableArray *imageUrlArray;
//行情
@property (nonatomic , strong) NSMutableArray *quotationModelArray;
//公告
@property (nonatomic , strong) NSMutableArray *noticeModelArray;

//当前页码
@property (nonatomic , assign) NSInteger currentPage;

@end

@implementation YDHomeViewController

-(NSMutableArray *)dynamicsModelArray
{
    if (_dynamicsModelArray == nil) {
        _dynamicsModelArray = [NSMutableArray array];
    }
    return _dynamicsModelArray;
}
-(NSMutableArray *)optionsDynamicsModelArray
{
    if (_optionsDynamicsModelArray == nil) {
        _optionsDynamicsModelArray = [NSMutableArray array];
    }
    return _optionsDynamicsModelArray;
}
-(NSMutableArray *)reModelArray
{
    if (_reModelArray == nil) {
        _reModelArray = [NSMutableArray array];
    }
    return _reModelArray;
}
-(NSMutableArray *)carsoulModelArray
{
    if (_carsoulModelArray == nil) {
        _carsoulModelArray = [NSMutableArray array];
    }
    return _carsoulModelArray;
}

-(NSMutableArray *)imageUrlArray
{
    if (_imageUrlArray == nil) {
        _imageUrlArray = [NSMutableArray array];
    }
    return _imageUrlArray;
}
-(NSMutableArray *)quotationModelArray
{
    if (_quotationModelArray == nil) {
        _quotationModelArray = [NSMutableArray array];
    }
    return _quotationModelArray;
}
-(NSMutableArray *)noticeModelArray
{
    if (_noticeModelArray == nil) {
        _noticeModelArray = [NSMutableArray array];
    }
    return _noticeModelArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self tableView];
    [self topBarView];//顶部工具栏
    [self setUpDataManger];
    [self reslveStoreData];
    [self loadData];
    [self netStatusMonitor];
    [self versionInformation];
    [self addNotification];
}


- (void)netStatusMonitor
{
    //实时监听网络状态
    [[NetStatusManger shareinstance] netWorkStatusWithBlock:^(NetworkStatusType type) {
        if (type == NetworkStatusNotReachable) {
            [[NavTipsView defaultTipsView] showAlwaysInView:self.view text:@"当前网络不可用"];
        }else
        {
            [[NavTipsView defaultTipsView] hide];
        }
    }];
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self viewStopTimer];
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self viewOpenTimer];
}
/******顶部视图************/
-(YDHomeTopView *)topView
{
    if (_topView == nil) {
        YDHomeTopView *topView = [YDHomeTopView homeTopViewWithCarsoulImageUrlArray:self.imageUrlArray NoticeModelArray:self.noticeModelArray QuotationModelArray:self.quotationModelArray];
        CGRect topViewFrame;
        if (isPhoneX) {
            topViewFrame = CGRectMake(0, 0, LKScreenW, rateX812(333));
        }else{
            topViewFrame = CGRectMake(0, 0, LKScreenW, rate750(333));
        }
        topView.frame = topViewFrame;
        topView.y = -topView.height;
        topView.delegate = self;
        self.tableView.tableHeaderView = topView;
        
        _topView = topView;
    }
    return _topView;
}

/*******顶部工具栏**********/
-(YDHomeTopBarView *)topBarView
{
    if (_topBarView == nil) {
        YDHomeTopBarView *topBarView = [[YDHomeTopBarView alloc] init];
        [self.view addSubview:topBarView];
        topBarView.delegate = self;
        [topBarView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.left.right.equalTo(self.view);
            make.top.equalTo(self.view);
            if (isPhoneX) {
                make.height.equalTo(@88);
            }else{
                make.height.equalTo(@64);
            }
        }];
        _topBarView = topBarView;
    }
    return _topBarView;
}
#pragma SYHomeTopBarViewDelegate
-(void)homeTopBarView:(YDHomeTopBarView *)topBarView buttonCLick:(SYNoHeightedButton *)button
{
    if (button.tag == 1) {//客服

        NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",CustomerPhone];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
//        DDLog(@"客服")
    }else if (button.tag == 2){//询问
        YDQuestionController *vc = [[YDQuestionController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
//搜索界面
-(void)homeTopBarViewSearchImageCLick:(YDHomeTopBarView *)topBarView
{
    YDStockSearchViewController *vc = [[YDStockSearchViewController alloc] init];
    vc.searchString = @"";
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:NO];
}

/*******tableView********/
-(UITableView *)tableView
{
    if (_tableView == nil) {
        CGFloat safeBottomH = isPhoneX ? 83 : 49;
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, self.view.height - safeBottomH) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.backgroundColor = [UIColor colorWithHexString:mainGray];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
        _tableView = tableView;
    }
    return _tableView;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
//    if ([keyPath isEqualToString:@"contentOffset"]){
//        CGPoint offset = [change[NSKeyValueChangeNewKey] CGPointValue];
//        if (isPhoneX) {
//            if (offset.y >= (rateX812(365) - 88)) {//rateX812(333) + rateX812(32) - 88
//                self.tableView.contentInset = UIEdgeInsetsMake(88, 0, 0, 0);
//            }else{
//                self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
//            }
//        }else{
//            if (offset.y >= (rate750(365) - 64)) {//rate750(333) + rate750(32) - 64
//                self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
//            }else{
//                self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
//            }
//        }
//    }
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat defaultH = isPhoneX ? rateX812(210) : rate750(210);
    CGFloat offsetY = scrollView.contentOffset.y;

    if (offsetY < 0) {
        self.topBarView.hidden = YES;
    }else{
        self.topBarView.hidden = NO;
    }
    CGFloat h = offsetY;
    if (h >= defaultH) {
        h = defaultH;
    }
    CGFloat alpha = 1.0 * offsetY  / 100;
    if (alpha >= 1.0) {
        alpha = 0.99;
    }
    self.topBarView.backgroundColor = [UIColor colorWithHexString:@"0E4483" alpha:alpha];
}
/*************UITableViewDelegate , UITableViewDataSource************/
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //期权
    return self.optionsDynamicsModelArray.count;
//    return 1000;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //期权
    return isPhoneX ? rateX812(70) : rate750(70);
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//    return isPhoneX ? rateX812(32) : rate750(32);
    return isPhoneX ? rateX812(5) : rate750(5);
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //期权交易动态
    YDHomeOptionsCell *cell = [YDHomeOptionsCell cellWithTableView:tableView];
    cell.delegate = self;
    YDHomeOptionsDynamicModel *model = self.optionsDynamicsModelArray[indexPath.row];
    cell.model = model;
    return cell;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDHomeOptionsDynamicModel *model = self.optionsDynamicsModelArray[indexPath.row];
    YDVerticalStockBuyController *vc = [[YDVerticalStockBuyController alloc] init];
    vc.isActivity = NO;
    vc.isNormal = YES;
    vc.optionStyle = SYVerticalStockButtonOptionViewStyle3;
    vc.stockCode = model.stockCode;
    vc.stockName = model.stockName;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
//    YDQHomeTableViewHeader *headerView = [YDQHomeTableViewHeader headerViewWithTableView:tableView];
//    return headerView;
    
    
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor colorWithHexString:mainGray];
    return view;
}

#pragma 期权cell上的按钮点击
-(void)homeOptionsCellSaleButtonClick:(YDHomeOptionsCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    YDHomeOptionsDynamicModel *model = self.optionsDynamicsModelArray[indexPath.row];
    YDBuyOptionsViewController *vc = [[YDBuyOptionsViewController alloc] init];
    vc.stockCode = model.stockCode;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

/***********SYHomeTableViewHeaderViewDelegate***************/
-(void)homeTableViewHeaderView:(YDHomeTableViewHeaderView *)headerView didClickButtonTag:(NSInteger)buttonTag
{
    if (buttonTag == 0) {
        self.dataStyle = SYHomeViewControllerDataSaleStatus;
        [self.tableView reloadData];
    }else{
        self.dataStyle = SYPositionViewControllerDataOptions;
        [self.tableView reloadData];
    }
    
    [self loadTableViewData];
}
-(void)setUpDataManger
{
    MJGIFHeader *header = [MJGIFHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    //隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES ;
    //隐藏状态
    header.stateLabel.hidden = YES ;
    self.tableView.mj_header = header;
    
    MJGIFFooter *footer = [MJGIFFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTableViewData)];
    footer.stateLabel.hidden = YES;
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
    

}

-(void)loadData
{
    //加载推荐股票数据
    [self loadTableViewData];
//#warning 加载轮播、行情、公告数据
    [self loadCarsoulSalePostData];
}
/////*******加载交易动态和推荐股票数据**********/////
-(void)loadTableViewData
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(0) forKey:@"page"];
    [dict setObject:@(10) forKey:@"size"];
    [[SYProgressHUD sharedInstance] showMBHudWithString:@"加载中~" SuperView:self.view];
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:HomeOptionsSaleData WithSuccessBlock:^(NSDictionary *resultDict) {
        DDLog(@"%@" , resultDict)
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [self.tableView.mj_header endRefreshing];
        if ([resultDict[@"code"] integerValue] == 200) {
            self.currentPage = [resultDict[@"result"][@"number"] integerValue] + 1;

            
            [self.optionsDynamicsModelArray removeAllObjects];
            self.optionsDynamicsModelArray = [YDHomeOptionsDynamicModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"content"]];
            [self.tableView reloadData];
            
            if (self.optionsDynamicsModelArray.count < 10) {
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshing];
            }
            
            //存储一下期权动态数据
            [self restoreHomeDataWithDataKey:storeHomeOptionsDataID dataDict:resultDict[@"result"][@"content"]];
            
        }else{
            self.tableView.mj_footer.hidden = YES;
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"message"] isExistNav:NO];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [self.tableView.mj_header endRefreshing];
        self.tableView.mj_footer.hidden = NO;
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:NO];
    }];
}

-(void)loadMoreTableViewData
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(self.currentPage) forKey:@"page"];
    [dict setObject:@(10) forKey:@"size"];
    [[SYProgressHUD sharedInstance] showMBHudWithString:@"加载中~" SuperView:self.view];
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:HomeOptionsSaleData WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [self.tableView.mj_footer endRefreshing];
        if ([resultDict[@"code"] integerValue] == 200) {
            self.currentPage = [resultDict[@"result"][@"number"] integerValue] + 1;
            
            
            NSArray *reArray =  [YDHomeOptionsDynamicModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"content"]];
            [self.optionsDynamicsModelArray addObjectsFromArray:reArray];
            [self.tableView reloadData];
            if (reArray.count < 10) {
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
                [self.tableView.mj_footer endRefreshing];
            }
            
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"message"] isExistNav:NO];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [self.tableView.mj_footer endRefreshing];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:NO];
    }];
}
////////********加载轮播 ， 行情 ， 公告信息**********///////
-(void)loadCarsoulSalePostData
{
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetHomeTopData WithSuccessBlock:^(NSDictionary *resultDict) {
        
        DDLog(@"resultDict = %@" , resultDict)
        
        if ([resultDict[@"code"] integerValue] == 200) {
            //轮播信息
            self.carsoulModelArray = [YDHomeCarsoulModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"bannerList"]];
            [self.imageUrlArray removeAllObjects];
            for (YDHomeCarsoulModel *model in self.carsoulModelArray) {
                [self.imageUrlArray addObject:model.link];
            }
            self.noticeModelArray = [YDHomeRotationModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"circularsList"]];
            
            self.quotationModelArray = [YDHomeMarketModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"stockMarketIndexList"]];
            
            if (_topView) {
                self.topView.carsoulImageUrlArray = self.imageUrlArray;
                self.topView.noticeModelArray = self.noticeModelArray;
                self.topView.quotationModelArray = self.quotationModelArray;
            }else{
               [self topView];
            }
            
            [self restoreHomeDataWithDataKey:storeHomeMarketDataID dataDict:resultDict[@"result"]];
            
        }else{
            DDLog(@"首页轮播信息加载出错")
        }
    } failBlock:^(NSError *error) {
        DDLog(@"%@",error)
        DDLog(@"首页轮播信息加载出错")
    }];

}


/**************8SYHomeTopViewDelegate*****************/
-(void)homeTopView:(YDHomeTopView *)topView didSelectedViewType:(SYHomeTopViewStyle)viewStyle viewIndex:(NSInteger)index
{
    if (viewStyle == SYHomeTopViewStyleCarsoul) {//轮播

        YDHomeCarsoulModel *model = self.carsoulModelArray[index];
        if ([model.forward isEqualToString:@"AppBuy"])
        {
            //跳点买 默认平安银行
            YDVerticalStockBuyController *vc = [[YDVerticalStockBuyController alloc] init];
            vc.isActivity = YES;
            vc.stockName = @"平安银行";
            vc.stockCode = @"000001";
            vc.isNormal = YES;
            vc.optionStyle = SYVerticalStockButtonOptionViewStyle3;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
            
            

        }else if ([model.forward isEqualToString:@"AppGuide"])
        {
            //跳新手H5
            YDOptionsModeController *vc = [[YDOptionsModeController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            vc.title = @"模式案例";
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if ([model.forward isEqualToString:@"AppPromotion"])
        {
            //跳推广赚钱
            YDTuiGuangViewController *vc = [[YDTuiGuangViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if ([model.forward isEqualToString:@"AppExperience"])
        {
            YDAdvertViewController *vc = [[YDAdvertViewController alloc] init];
            vc.urlStr = twoQianBaseUrl;
            vc.title = @"免费体验";
            [self.navigationController pushViewController:vc animated:YES];
        }
        else
        {
            //跳点买分栏
            self.tabBarController.selectedIndex = 1;
            
        }
    }else if (viewStyle == SYHomeTopViewStyleMarket){//行情
        if (!self.quotationModelArray.count)return;
        for (YDHomeMarketModel *model in self.quotationModelArray) {
            model.isSelected = NO;
        }
        
        YDHomeMarketModel *model = self.quotationModelArray[index];
        model.isSelected = YES;
        YDStockMarketDetailController *vc = [[YDStockMarketDetailController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.isNormal = YES;
        vc.marketModelArray = self.quotationModelArray;
        vc.stockName = model.name;
        vc.stockCode = model.code;
        vc.index = index;
        [self.navigationController pushViewController:vc animated:YES];
        
//        DDLog(@"行情%zd",index)
    }else{//公告
//        DDLog(@"公告%zd",index)
        if (self.noticeModelArray.count) {//有公告数据
            if (index+1 > self.noticeModelArray.count)return;
            //获取模型
            YDHomeRotationModel *model = self.noticeModelArray[index];
            if (model.href.length) {
                
                YDWebViewController *vc = [[YDWebViewController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                vc.urlStr = model.href;
                [self.navigationController pushViewController:vc animated:YES];
                
            }
 
        }
        
    }
}


//首页数据缓存处理
-(void)restoreHomeDataWithDataKey:(NSString *)dataKey dataDict:(NSDictionary *)dict
{
    
    dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_resume(source);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //获取数据库
        LKKeyValueStore *store = [LKKeyValueStore sharedInstanceWithdbName:peizidbName];
        if ([store isExistTableWithName:storeHomeDataKey]) {//存在首页信息表
            
            [store putObject:dict withId:dataKey intoTable:storeHomeDataKey];
            
        }else{//不存在
            [store createTableWithName:storeHomeDataKey];
            
            [store putObject:dict withId:dataKey intoTable:storeHomeDataKey];
            
        }
        dispatch_source_merge_data(source, 1);
    });
    
    
}
//获取存储的数据
-(id)getHomeStockDataWithDataId:(NSString *)dataId
{
    //获取数据库
    LKKeyValueStore *store = [LKKeyValueStore sharedInstanceWithdbName:peizidbName];
    if ([store isExistTableWithName:storeHomeDataKey]) {//存在首页信息表
        id obj = [store getObjectById:dataId fromTable:storeHomeDataKey];
        return obj;
    }else{
        return nil;
    }
}
//界面加载，处理缓存数据
-(void)reslveStoreData
{
    LKKeyValueStore *store = [LKKeyValueStore sharedInstanceWithdbName:peizidbName];
    if ([store isExistTableWithName:storeHomeDataKey]) {
        //获取股票期权交易动态
        id optionsDataObj = [self getHomeStockDataWithDataId:storeHomeOptionsDataID];
        if (optionsDataObj) {
            NSArray *optionsDataArray = (NSArray *)optionsDataObj;
            self.optionsDynamicsModelArray = [YDHomeOptionsDynamicModel mj_objectArrayWithKeyValuesArray:optionsDataArray];
        }
        //获取大盘数据
        id marketDataObj = [self getHomeStockDataWithDataId:storeHomeMarketDataID];
        if (marketDataObj) {
            NSDictionary *marketDict = (NSDictionary *)marketDataObj;
            
            self.carsoulModelArray = [YDHomeCarsoulModel mj_objectArrayWithKeyValuesArray:marketDict[@"bannerList"]];
            [self.imageUrlArray removeAllObjects];
            for (YDHomeCarsoulModel *model in self.carsoulModelArray) {
                [self.imageUrlArray addObject:model.link];
            }
            self.noticeModelArray = [YDHomeRotationModel mj_objectArrayWithKeyValuesArray:marketDict[@"circularsList"]];
            
            self.quotationModelArray = [YDHomeMarketModel mj_objectArrayWithKeyValuesArray:marketDict[@"stockMarketIndexList"]];
            
        }
        [self.tableView reloadData];
        [self topView];
        
    }else{//不存在
        return;
    }
}


//******开始通知*******//
-(void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewOpenTimer) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewStopTimer) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewStopTimer) name:UIApplicationWillTerminateNotification object:nil];
}

-(void)dealloc
{
    [self.tableView removeObserver:self forKeyPath:@"contentOffset"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)versionInformation
{
    dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_resume(source);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[SYVersionManger sharedInstance] loadAppVersionInformation];
        
        [self loadReStockDataForOption];
        
        dispatch_source_merge_data(source, 1);
    });
}

-(void)viewOpenTimer
{
    if (self.marketTimer)return;
    if (![NSDate stockTradingTimeJudgment])return;
    DDLog(@"开启定时器")
    self.marketTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timeLoadMarketDetailData) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.marketTimer forMode:NSRunLoopCommonModes];
}
-(void)viewStopTimer
{
    if (!self.marketTimer)return;
    DDLog(@"关闭定时器")
    [self.marketTimer invalidate];
    self.marketTimer = nil;

}

-(void)timeLoadMarketDetailData
{
    if (self.marketIsRunning)return;
    self.marketIsRunning = YES;
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetHomeTopData WithSuccessBlock:^(NSDictionary *resultDict) {
        self.marketIsRunning = NO;
        if ([resultDict[@"code"] integerValue] == 200) {
            [self.quotationModelArray removeAllObjects];
            self.quotationModelArray = [YDHomeMarketModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"stockMarketIndexList"]];
            
            if (_topView) {
                self.topView.quotationModelArray = self.quotationModelArray;
            }else{
                [self topView];
            }
        }else{
        }
    } failBlock:^(NSError *error) {
        self.marketIsRunning = NO;
    }];
}

//加载一次推荐股票的数据，自选那里用到
-(void)loadReStockDataForOption
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(0) forKey:@"page"];
    [dict setObject:@(10) forKey:@"size"];
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:GetHomeSaleReData WithSuccessBlock:^(NSDictionary *resultDict) {
        if ([resultDict[@"code"] integerValue] == 200) {
            //存储一下推荐股票数据数据
            [self restoreHomeDataWithDataKey:storeHomeReDataID dataDict:resultDict[@"result"][@"content"]];
        }else{
        }
    } failBlock:^(NSError *error) {
    }];
}

@end
